#pragma once
#include "db.hpp"
#include "matcher.hpp"
#include "session.hpp"
#include "online.hpp"
#include "room.hpp"
#include "util.hpp"
/*
网络服务
*/
const static std::string WWWROOT = "wwwroot/";

class server
{
private:
    void file_handler(wsserver_t::connection_ptr &conn)
    {
        // 静态请求
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        std::string filepath = _web_root + uri;
        if (filepath.back() == '/')
        {
            filepath += "login.html";
        }
        std::string body;
        bool ret = file_util::read(filepath, body);
        if (ret == false)
        {
            // file_util::read("./webroot/404.html", body);
            body += "<html>";
            body += "<head>";
            body += "<meta charset='UTF-8'/>";
            body += "</head>";
            body += "<body>";
            body += "<h1> Not Found </h1>";
            body += "</body>";
            conn->set_status(websocketpp::http::status_code::not_found);
            conn->set_body(body);
            return;
        }
        conn->set_body(body);
        conn->set_status(websocketpp::http::status_code::ok);
    }
    void http_resp(wsserver_t::connection_ptr &conn, bool result,
                   websocketpp::http::status_code::value code, const std::string &reason)
    {
        Json::Value resp_json;
        resp_json["result"] = result;
        resp_json["reason"] = reason;
        std::string resp_body;
        json_util::serialize(resp_json, resp_body);
        conn->set_body(resp_body);
        conn->set_status(code);
        conn->append_header("Content-Type", "application/json");
        return;
    }
    void reg(wsserver_t::connection_ptr &conn)
    {
        // 用户注册逻辑
        std::string req_body = conn->get_request_body();
        Json::Value login_info;
        if (!json_util::unserialize(req_body, login_info) || login_info["username"].isNull() || login_info["password"].isNull())
        {
            LOG(DEBUG, "reg eroor\n");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名或密码");
        }
        if (!_user_m.registers(login_info))
        {
            LOG(DEBUG, "reg eroor\n");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名已经被占用!");
        }
        LOG(INFO, "注册用户成功\n");
        return http_resp(conn, true, websocketpp::http::status_code::ok, "注册用户成功");
    }
    void login(wsserver_t::connection_ptr &conn)
    {
        // 用户登录逻辑
        std::string req_body = conn->get_request_body();
        Json::Value login_info;
        if (!json_util::unserialize(req_body, login_info) || login_info["username"].isNull() || login_info["password"].isNull())
        {
            LOG(DEBUG, "login eroor\n");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "请输入用户名或密码");
        }
        if (!_user_m.login(login_info))
        {
            LOG(DEBUG, "login eroor\n");
            return http_resp(conn, false, websocketpp::http::status_code::bad_request, "用户名或密码错误");
        }
        uint64_t uid = login_info["id"].asUInt64();
        session_ptr ssp = _session_m.create_session(uid, LONGIN);
        if (ssp.get() == nullptr)
        {
            LOG(DEBUG, "session create error\n");
            return http_resp(conn, false, websocketpp::http::status_code::internal_server_error, "创建会话失败");
        }

        _session_m.set_session_expired_time(ssp->ssid(), SESSION_TIMEOUT);
        // 设置响应头部：Set-Cookie,将sessionid通过cookie返回
        std::string cookie_ssid = "SSID=" + std::to_string(ssp->ssid());
        conn->append_header("Set-Cookie", cookie_ssid);
        LOG(INFO, "用户登录成功\n");
        return http_resp(conn, true, websocketpp::http::status_code::ok, "用户登录成功");
    }

    bool get_cookie_val(std::string &cookie_str, const std::string &key, std::string &val)
    {
        // Cookie: SSID=XXX; path=/;
        // 1. 以 ; 作为间隔，对字符串进行分割，得到各个单个的cookie信息
        std::string sep = "; ";
        std::vector<std::string> cookie_arr;
        string_util::split(cookie_str, sep, cookie_arr);

        for (auto str : cookie_arr)
        {
            // 2. 对单个cookie字符串，以 = 为间隔进行分割，得到key和val
            std::vector<std::string> tmp_arr;
            string_util::split(str, "=", tmp_arr);
            if (tmp_arr.size() != 2)
            {
                continue;
            }
            if (tmp_arr[0] == key)
            {
                val = tmp_arr[1];
                return true;
            }
        }
        return false;
    }

    void info(wsserver_t::connection_ptr &conn)
    {
        std::string cookie_head = conn->get_request_header("Cookie");
        std::string ssid_str;
        if (cookie_head.empty() || !get_cookie_val(cookie_head, "SSID", ssid_str))
        {
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "找不到cookie信息，请重新登录");
            return;
        }

        session_ptr ssid_ptr = _session_m.get_session_by_sid(std::stol(ssid_str));
        if (ssid_ptr.get() == nullptr)
        {
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "登录过期，请重新登录");
            return;
        }

        std::string body;
        Json::Value user_info;
        if (!_user_m.select_by_id(ssid_ptr->uid(), user_info))
        {
            http_resp(conn, false, websocketpp::http::status_code::bad_request, "未注册用户");
            return;
        }

        json_util::serialize(user_info, body);
        conn->set_body(body);
        conn->append_header("Content-Type", "application/json");
        conn->set_status(websocketpp::http::status_code::ok);

        // 重新刷新Cookie信息
        _session_m.set_session_expired_time(ssid_ptr->ssid(), SESSION_TIMEOUT);
    }
    void http_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string method = req.get_method();
        std::string uri = req.get_uri();
        if (method == "POST" && uri == "/reg")
        {
            return reg(conn);
        }
        else if (method == "POST" && uri == "/login")
        {
            return login(conn);
        }
        else if (method == "GET" && uri == "/info")
        {
            return info(conn);
        }
        else
        {
            return file_handler(conn);
        }
    }

    void ws_resp(wsserver_t::connection_ptr conn, Json::Value &resp)
    {
        std::string body;
        json_util::serialize(resp, body);
        conn->send(body);
    }

    session_ptr get_session_by_cookie(wsserver_t::connection_ptr conn)
    {
        Json::Value err_resp;
        std::string cookie_head = conn->get_request_header("Cookie");
        std::string ssid_str;
        if (cookie_head.empty() || !get_cookie_val(cookie_head, "SSID", ssid_str))
        {
            err_resp["optype"] = "hall_ready";
            err_resp["reason"] = "没有找到cookie信息，需要重新登录";
            err_resp["result"] = false;
            ws_resp(conn, err_resp);
            return session_ptr();
        }

        session_ptr ssid_ptr = _session_m.get_session_by_sid(std::stol(ssid_str));
        if (ssid_ptr.get() == nullptr)
        {
            err_resp["optype"] = "hall_ready";
            err_resp["reason"] = "登录过期请重新登录";
            err_resp["result"] = false;
            ws_resp(conn, err_resp);
            return session_ptr();
        }
        return ssid_ptr;
    }

    void wsopen_game_hall(wsserver_t::connection_ptr &conn)
    {
        Json::Value resp_json;
        // 获取登录信息
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            return;
        }

        // 判断用户是否已经在线
        uint64_t id = ssid_ptr->uid();
        if (_online_m.is_in_game_hall(id) || _online_m.is_in_game_room(id))
        {
            resp_json["optype"] = "hall_ready";
            resp_json["reason"] = "玩家重复登录！";
            resp_json["result"] = false;
            return ws_resp(conn, resp_json);
        }

        // 进入游戏大厅
        _online_m.enter_game_hall(id, conn);
        // 响应客户端，设置永久session
        resp_json["optype"] = "hall_ready";
        resp_json["result"] = true;
        ws_resp(conn, resp_json);

        _session_m.set_session_expired_time(ssid_ptr->ssid(), SESSION_FOREVER);
    }

    void wsopen_game_room(wsserver_t::connection_ptr &conn)
    {
        // 匹配就绪进入房间对战网页之后的 执行逻辑
        Json::Value resp_json;
        // 获取登录信息
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            return;
        }

        int64_t uid = ssid_ptr->uid();
        // 判断房间是否创建
        room_ptr rp = _room_m.get_room_by_uid(uid);
        if (rp.get() == nullptr)
        {
            resp_json["optype"] = "room_ready";
            resp_json["reason"] = "没有找到玩家的房间信息";
            resp_json["result"] = false;
            return ws_resp(conn, resp_json);
        }

        // 将当前用户添加到在线用户管理的游戏房间中
        _online_m.enter_game_room(uid, conn);
        LOG(INFO,"%llu\n",uid);
        _session_m.set_session_expired_time(ssid_ptr->ssid(), SESSION_FOREVER);
        // 回复房间准备完毕
        resp_json["optype"] = "room_ready";
        resp_json["result"] = true;
        resp_json["room_id"] = (Json::UInt64)rp->id();
        resp_json["uid"] = (Json::UInt64)uid;
        resp_json["white_id"] = (Json::UInt64)rp->get_white_user();
        resp_json["black_id"] = (Json::UInt64)rp->get_black_user();
        return ws_resp(conn, resp_json);
    }

    void wsopen_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            return wsopen_game_hall(conn);
        }
        else if (uri == "/room")
        {
            return wsopen_game_room(conn);
        }
    }

    void wsclose_game_hall(wsserver_t::connection_ptr conn)
    {
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            return;
        }

        _online_m.exit_game_hall(ssid_ptr->uid());

        _session_m.set_session_expired_time(ssid_ptr->ssid(), SESSION_TIMEOUT);
    }

    void wsclose_game_room(wsserver_t::connection_ptr conn)
    {
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            return;
        }

        _online_m.exit_game_room(ssid_ptr->uid());

        _session_m.set_session_expired_time(ssid_ptr->ssid(), SESSION_TIMEOUT);

        _room_m.remove_user(ssid_ptr->uid());
    }
    void wsclose_callback(websocketpp::connection_hdl hdl)
    {
        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            // 建立了游戏大厅的长连接
            return wsclose_game_hall(conn);
        }
        else if (uri == "/room")
        {
            // 建立了游戏房间的长连接
            return wsclose_game_room(conn);
        }
    }

    void wsmsg_game_hall(wsserver_t::connection_ptr conn, wsserver_t::message_ptr msg)
    {
        Json::Value resq;
        // 游戏大厅匹配
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            return;
        }

        // 获取请求信息
        std::string req_body = msg->get_payload();
        Json::Value req_json;
        bool ret = json_util::unserialize(req_body, req_json);
        if (ret == false || req_json["optype"].isNull())
        {
            resq["result"] = false;
            resq["reason"] = "请求错误";
            return ws_resp(conn, resq);
        }

        if (req_json["optype"].asString() == "match_start")
        {
            LOG(INFO,"match_start\n");
            _macher.add(ssid_ptr->uid());
            resq["optype"] = "match_start";
            resq["result"] = true;
            return ws_resp(conn, resq);
        }
        else if (req_json["optype"].asString() == "match_stop")
        {
            _macher.del(ssid_ptr->uid());
            resq["optype"] = "match_stop";
            resq["result"] = true;
            return ws_resp(conn, resq);
        }
        resq["optype"] = "unknow";
        resq["result"] = false;
        resq["reason"] = "请求错误";
        ws_resp(conn, resq);
    }
    void wsmsg_game_room(wsserver_t::connection_ptr conn, wsserver_t::message_ptr msg)
    {
        Json::Value resq;
        // 游戏大厅匹配
        session_ptr ssid_ptr = get_session_by_cookie(conn);
        if (ssid_ptr.get() == nullptr)
        {
            LOG(DEBUG, "未找到玩家的session id\n");
            return;
        }
        // 2. 获取客户端房间信息
        room_ptr rp = _room_m.get_room_by_uid(ssid_ptr->uid());
        if (rp.get() == nullptr)
        {
            resq["optype"] = "unknow";
            resq["reason"] = "没有找到玩家的房间信息";
            resq["result"] = false;
            LOG(DEBUG, "房间-没有找到玩家房间信息\n");
            return ws_resp(conn, resq);
        }
        // 获取请求信息
        std::string req_body = msg->get_payload();
        Json::Value req_json;
        bool ret = json_util::unserialize(req_body, req_json);
        if (ret == false)
        {
            resq["optype"] = "unknow";
            resq["result"] = false;
            resq["reason"] = "请求错误";
            LOG(DEBUG, "房间请求解析失败\n");
            return ws_resp(conn, resq);
        }

        rp->handle_request(req_json);
    }
    void wsmsg_callback(websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
    {

        wsserver_t::connection_ptr conn = _wssrv.get_con_from_hdl(hdl);
        websocketpp::http::parser::request req = conn->get_request();
        std::string uri = req.get_uri();
        if (uri == "/hall")
        {
            return wsmsg_game_hall(conn, msg);
        }
        else if (uri == "/room")
        {
            return wsmsg_game_room(conn, msg);
        }
    }

public:
    server(const std::string &host,
           const std::string &user,
           const std::string &pass,
           const std::string &dbname,
           int port = 3306,
           const std::string &wwwroot = WWWROOT)
        : _web_root(wwwroot),
          _user_m(host.c_str(), user.c_str(), pass.c_str(), dbname.c_str(), port),
          _room_m(&_user_m, &_online_m),
          _session_m(&_wssrv),
          _macher(&_online_m, &_user_m, &_room_m)
    {
        _wssrv.set_access_channels(websocketpp::log::alevel::none);
        _wssrv.init_asio();
        _wssrv.set_reuse_addr(true);
        _wssrv.set_http_handler(std::bind(&server::http_callback, this, std::placeholders::_1));
        _wssrv.set_open_handler(std::bind(&server::wsopen_callback, this, std::placeholders::_1));
        _wssrv.set_close_handler(std::bind(&server::wsclose_callback, this, std::placeholders::_1));
        _wssrv.set_message_handler(std::bind(&server::wsmsg_callback, this, std::placeholders::_1, std::placeholders::_2));
    }
    /*启动服务器*/
    void start(int port)
    {
        _wssrv.listen(port);
        _wssrv.start_accept();
        _wssrv.run();
    }

private:
    std::string _web_root;
    wsserver_t _wssrv;
    user_table _user_m;
    online_manager _online_m;
    room_manager _room_m;
    session_manager _session_m;
    macher _macher;
};
